#include "upper_com_protocol.h"
#include "btla_protocol.h"
#include "tlmbms_protocol.h"
#include "usbd_cdc_if.h"
#include "cmsis_os.h"
#include "main.h"
#include <string.h>
#include "task_modbus.h"

void upper_com_receive(uint8_t* Buf, uint32_t Len){
    if(Buf[0]==':'&&Buf[6]=='\r'&&Buf[7]=='\n'){
        // 设定PCS功率
        dev_operation_mode_t mode;
        mode.op_mode = 0x22;
        mode.para1 = *(int32_t*)(Buf+2); //负为放电
        mode.para2 = 0;
        mode.para3 = 0;
        mode.para4 = 0;
        write_operation_mode(get_modbusH_1(), &mode);
        // 开停机指令
        if(Buf[1]==1){
            write_start_stop_CMD(get_modbusH_1(), true);
        }
        else if(Buf[1]==0){
            write_start_stop_CMD(get_modbusH_1(), false);
        }
    }
}

void upper_com_transmit(){
    static uint8_t data[43]={0};

    static upper_com_t upper_data;
    upper_data.dc_0_001V = get_DC_0_001V();
    upper_data.dc_0_001A = get_DC_0_001A();
    upper_data.dc_W = get_DC_W();
    upper_data.ac_0_001V = get_grid_0_001V();
    upper_data.ac_0_001A = get_grid_0_001A();
    upper_data.ac_W = get_sys_W();
    upper_data.ac_Var = get_sys_Var();
    upper_data.ac_0_01Hz = *get_0_01Hz();
    upper_data.bms_SOC = *get_bms_SOC();
    upper_data.bms_max_0_0001V = *get_bms_max_0_0001V();
    upper_data.bms_min_0_0001V = *get_bms_min_0_0001V();
    upper_data.bms_max_0_1T = *get_bms_max_0_1T();
    upper_data.bms_min_0_1T = *get_bms_min_0_1T();

    memcpy(data+1,(uint8_t *)&upper_data,sizeof(upper_data));
    data[0] = ':';
    data[41] = '\r';
    data[42] = '\n';
    CDC_Transmit_HS((uint8_t*)data,43);
}